package marmalius.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapService {
	private static final MapService instance = new MapService();
	private Map<Integer, Map<Integer, Region>> regions;
	
	public MapService() {
		regions = new HashMap<Integer, Map<Integer, Region>>();
	}
	
	public List<Region> getRegions(int absX, int absY) {
		List<Region> needRegion = new ArrayList<Region>();
		absX -= 48; //48 => 6 Regions
		absY -= 48;
		int startRegionX = getRegionCoord(absX);
		int startRegionY = getRegionCoord(absY);
		
		int stopRegionX = startRegionX + 12; //12 => 2 * 6 Regions
		int stopRegionY = startRegionY + 12;
		
		for (int x = startRegionX; x < stopRegionX; x++) {
			Map<Integer, Region> tmpx = regions.get(x);
			if (tmpx == null)
				continue;
			for (int y = startRegionY; y < stopRegionY; y++) {
				if (tmpx.containsKey(y))
					needRegion.add(tmpx.get(y));
			}
		}
		
		return needRegion;
	}
	
	public Region getRegionXY(int x, int y) { //not use
		return getRegion(getRegionCoord(x), getRegionCoord(y));
	}
	
	public void addObject(SpawnObject object) {
		int rx = getRegionCoord(object.getCoordX());
		int ry = getRegionCoord(object.getCoordY());
		
		if (!regions.containsKey(rx))
			regions.put(rx, new HashMap<Integer, Region>());
		if (!regions.get(rx).containsKey(ry))
			regions.get(rx).put(ry, new Region());
		
		regions.get(rx).get(ry).addObject(object);
	}
	
	public void removeObject(SpawnObject object) {
		int rx = getRegionCoord(object.getCoordX());
		int ry = getRegionCoord(object.getCoordY());
		
		if (!regions.containsKey(rx) || !regions.get(rx).containsKey(ry))
			return ;
		
		regions.get(rx).get(ry).removeObject(object);
	}
	
	private Region getRegion(int rX, int rY) {
		if (regions.containsKey(rX) && regions.get(rX).containsKey(rY))
			return regions.get(rX).get(rY);
		else
			return null;
	}
	
	public static MapService getInstance() { return instance; }
	
	private int getRegionCoord(int xy) {
		return (int)Math.ceil(xy / 8.0);
	}
}
